package com.wxy.demo.rocketmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author e-Xiaoyuan.Wang
 * @since 2022/11/7 17:25
 */
@Slf4j
public class ConsumerDemo {
    public static void main(String[] args) throws Exception {

        //创建一个消息接收对象consumer
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
        //设定接收消息的命名服务器地址---获取到消息服务器ip
        consumer.setNamesrvAddr("127.0.0.1:9876");
        //设置接收消息对应的topic，对应的sub标签为任意*，之前producer没有指定tag。如果producer发送的消息指定了tag，那么也必须指定相应的tag
        consumer.subscribe("topic1", "*");
        //开启监听，用于接收消息
        consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
                //遍历接收到的消息
                for (MessageExt msg : list) {
                    log.info("接收消息：queue = {}, topic = {}, content = {}", msg.getQueueId(), msg.getTopic(), new String(msg.getBody()));
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        //启动消息接收服务
        consumer.start();

    }
}
